//
//  FMPropertyHelper.m
//  WOM
//
//  Created by leeqb on 12/5/13.
//  Copyright (c) 2013 cst. All rights reserved.
//

#import "FMPropertyHelper.h"

#define DEF_PLIST   @"PropertyList" // 存放从WindRunner.plist文件中读取出来的NSDictionary

@implementation FMPropertyHelper

// 读取WOM.plist文件，初始化应用相关的属性列表
+ (void)initPropertyList
{
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"WindRunner" ofType:@"plist"];
    NSString *sandboxPath = [NSString stringWithFormat:@"%@/%@", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"], @"WOM.plist"];
    
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if([fileManager fileExistsAtPath:sandboxPath]) {
        [fileManager removeItemAtPath:sandboxPath error:&error];
        if(error) {
            GCLog(@"%@", error);
        }
    }
    
    [fileManager copyItemAtPath:bundlePath toPath:sandboxPath error:&error];
    if(error) {
        GCLog(@"%@", error);
    }
    
    NSDictionary *plist = [[NSDictionary alloc] initWithContentsOfFile:sandboxPath];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:plist forKey:DEF_PLIST];
    [userDefaults synchronize];
}

// 获取WOM.plist文件中的属性值，多层级用/隔开。例如，参数传值为“key1/key2/key3”，将会取出key3的值
+ (NSObject *)valueOfPropertyKey:(NSString *)keyPath
{
    NSArray *subKeys = [keyPath componentsSeparatedByString:@"/"];
    
    NSDictionary *propertyList = [[NSUserDefaults standardUserDefaults] objectForKey:DEF_PLIST];
    if(subKeys.count == 1) {
        return [propertyList valueForKey:keyPath];
    } else if(subKeys.count > 1) {
        NSDictionary *temp = [propertyList objectForKey:[subKeys objectAtIndex:0]];
        if(!temp) {
            return nil;
        }
        
        for(int i=1; i<subKeys.count-1; i++) {
            temp = [temp objectForKey:[subKeys objectAtIndex:i]];
            if(!temp) {
                return nil;
            }
        }
        return [temp objectForKey:[subKeys objectAtIndex:(subKeys.count-1)]];
    } else {
        return nil;
    }
}

@end
